﻿using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.DirectoryServices;
using System.DirectoryServices.Protocols;
using MSU_Broker;

namespace MSU_WebServices
{
    public partial class WSMSU : System.Web.Services.WebService
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="User"></param>
        /// <returns></returns>
        [WebMethod]
        public DataTable LoadCourse(MSU_User User)
        {
            DataTable dtCourses = new DataTable("Courses");
            try
            {
                //Courses
                Object currentCoursesReturn = null;
                currentCoursesReturn = callMethod("get_my_courses_byusername", User.Moodle_Client, User.Moodle_SessionKey, User.UserName, "");

                dtCourses.Columns.Add("id");
                dtCourses.Columns.Add("fullname");
                dtCourses.Columns.Add("shortname");
                dtCourses.Columns.Add("summary");

                Array Courses = (Array)getProperty(currentCoursesReturn, "courses");

                for (int i = 0; i < Courses.Length; i++)
                {
                    dtCourses.Rows.Add(((string)getProperty(Courses.GetValue(i), "id")), ((string)getProperty(Courses.GetValue(i), "fullname")), ((string)getProperty(Courses.GetValue(i), "shortname")), ((string)getProperty(Courses.GetValue(i), "summary")));
                }
            }
            catch (Exception e)
            {
                MSU_Exception currentException = null;
                if (e is MSU_Exception)
                {
                    for (int i = 0; (i < ErrorsToScreen.Count) && (currentException == null); i++)
                    {
                        currentException = getInnerException(ErrorsToScreen[i], (MSU_Exception)e);
                    }
                }
                if (currentException == null)
                    currentException = new MSU_Exception("Unexpected error: " + e.Message, MSU_Error.UNEXPECTED_ERROR);

                throw MSU_ExceptionPack.PackSOAP("MoodleData", "http://tempuri.org/MSUWS", MSU_ExceptionPack.FaultCode.Server, currentException, ErrorsToScreen);

            }
            return dtCourses;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="User"></param>
        /// <param name="Adm"></param>
        /// <param name="CurrentCourse"></param>
        /// <param name="role"></param>
        /// <returns></returns>
        [WebMethod]
        public DataTable LoadCourseData(MSU_User User, MSU_Adm Adm, string CurrentCourse, ref string role)
        {
            DataTable dtGroups = new DataTable("Groups");
            try
            {
                string getMyIdReturn = (string)callMethod("get_my_id", User.Moodle_Client, User.Moodle_SessionKey);

                object groupsByCourseReturn = callMethod("get_groups_bycourse", User.Moodle_Client, User.Moodle_SessionKey, CurrentCourse, "id");

                object getMyGroupsReturn = callMethod("get_my_groups",User.Moodle_Client, User.Moodle_SessionKey, getMyIdReturn);

                Array courseGroups = (Array)getProperty(groupsByCourseReturn, "groups");
                Array myGroups = (Array)getProperty(getMyGroupsReturn, "groups");

                dtGroups.Columns.Add("id");
                dtGroups.Columns.Add("name");
                dtGroups.Columns.Add("description");

                for (int i = 0; i < courseGroups.Length; i++)
                {
                    for (int j = 0; j < myGroups.Length; j++)
                    {
                        if (((string)getProperty(courseGroups.GetValue(i), "name")) == ((string)getProperty(myGroups.GetValue(j), "name")))
                            dtGroups.Rows.Add(((string)getProperty(myGroups.GetValue(j), "id")), ((string)getProperty(myGroups.GetValue(j), "name")), ((string)getProperty(myGroups.GetValue(j), "description")));
                    }
                }

                //Using adm login
                string UsernameADM = Adm.MoodleUser;
                string PasswordADM = Adm.MoodlePass;
                object loginReturn = null;
                try
                {
                    loginReturn = callMethod("login", UsernameADM, PasswordADM);
                }
                catch (Exception e)
                {
                    if (findInnerException(INVALID_USERNAME_PASSWORD_MESSAGE_MOODLE, e))
                        throw new MSU_Exception("Invalid Moodle administrator username / or password.", MSU_Error.INVALID_MOODLE_ADMINISTRATOR_USERNAME_PASSWORD);
                    else
                        throw e;
                }

                string client = "";
                string sessionkey = "";
                try
                {
                    client = getProperty(loginReturn, "client").ToString();
                    sessionkey = getProperty(loginReturn, "sessionkey").ToString();
                }
                catch (Exception e)
                {
                    throw new MSU_Exception("Error on retrieve client/sessionkey from Moodle login data.", MSU_Error.RETRIEVE_MOODLE_LOGIN_DATA, e);
                }
                if (client == "")
                    throw new MSU_Exception("Error on retrieve client/sessionkey from Moodle login data.", MSU_Error.RETRIEVE_MOODLE_LOGIN_DATA);
             
                //Get The Role of the User
                string myRoleid = (string)callMethod("get_primaryrole_incourse",User.Moodle_Client, User.Moodle_SessionKey, User.UserName,"username", CurrentCourse, "id");

                object getRoleByIdReturn = callMethod("get_role_byid", client, sessionkey, myRoleid);

                Array myRoles = (Array)getProperty(getRoleByIdReturn, "roles");
                for (int i = 0; i < myRoles.Length; i++)
                    role += "<b>My Role in Course:</b> " + ((string)getProperty(myRoles.GetValue(i),"name"));
            }
            catch (Exception e)
            {
                MSU_Exception currentException = null;
                if (e is MSU_Exception)
                {
                    for (int i = 0; (i < ErrorsToScreen.Count) && (currentException == null); i++)
                    {
                        currentException = getInnerException(ErrorsToScreen[i], (MSU_Exception)e);
                    }
                }
                if (currentException == null)
                    currentException = new MSU_Exception("Unexpected error: " + e.Message, MSU_Error.UNEXPECTED_ERROR);
                throw MSU_ExceptionPack.PackSOAP("MoodleData", "http://tempuri.org/MSUWS", MSU_ExceptionPack.FaultCode.Server, currentException, ErrorsToScreen);
            }
            return dtGroups;
        }
    }
}
